package TankAgent;

import jade.content.ContentElement;
import jade.content.ContentManager;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.WakerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import wwtp.ontology.SendWater;
import wwtp.ontology.Water;
import DataBases.DirectWaterObject;

public class TankInflowWaterBehaviour extends CyclicBehaviour{

	protected MessageTemplate mt;
	protected ContentManager manager;
	
	@Override
	public void action() {
		// TODO Auto-generated method stub
		mt = MessageTemplate.and(MessageTemplate.MatchConversationId("Water"),MessageTemplate.MatchPerformative(ACLMessage.INFORM));
		manager = myAgent.getContentManager();
		final ACLMessage msg = myAgent.receive(mt);
        if (msg!=null){
    		try{
    		 	ContentElement ce = manager.extractContent(msg);
	   			if(ce instanceof SendWater){
	   				DirectWaterObject dwo = ((TankAgent)myAgent).dbDirectWater.exists (msg.getSender().getLocalName(), myAgent.getLocalName());
	   				myAgent.addBehaviour(new WakerBehaviour(myAgent,dwo.getTiempoDeTransito()) {
						
						@Override
						protected void handleElapsedTimeout() {
							// TODO Auto-generated method stub	
							
							//myAgent.addBehaviour(new ControlFluxBehaviour(msg));
							try{
								SendWater sw = (SendWater)manager.extractContent(msg);
								final Water water = sw.getWater();

								//Sending Water Data to the WWTP to be analized
								ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
							    msg.setConversationId("ControlFlowProtocol");
							    msg.setLanguage(((TankAgent)myAgent).codec.getName());
							    msg.setOntology(((TankAgent)myAgent).ontology.getName());

							    msg.addReceiver(new AID( ((TankAgent)myAgent).dbDirectWater.getLaminateWWTP(myAgent.getLocalName()),AID.ISLOCALNAME));
							    
							    System.out.println("\n"+myAgent.getLocalName() + " water recieved, sending info to -> "+ ((TankAgent)myAgent).dbDirectWater.getLaminateWWTP(myAgent.getLocalName()));
							    
							    myAgent.getContentManager().fillContent(msg,sw);
								myAgent.send(msg);
							}
							catch (Exception e){
								e.printStackTrace();
							}
						}
					});
	    		}
	    		
    		}
   			catch (Exception e) {
   				e.printStackTrace();
   			}
        } else {
        	block();
        }
	}

}
